package com.one.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.one.pojo.OneUser;
import com.one.pojo.Store;
import com.one.pojo.UserTrasRecord;
import com.one.service.OneUserService;
import com.one.service.StoreService;
import com.one.service.UserTrasRecordService;
import com.one.util.EhcacheCacheProvider;
import com.one.util.JSONResult;
import com.one.util.SMSWebChinese;
import com.one.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 用户交易管理
 * @Author semstouch
 * @Date 2017/4/9
 **/
@Controller
@ControllerAdvice
public class UserTrasRecordController extends AbstractJsonpResponseBodyAdvice {
    @Resource
    private UserTrasRecordService userTrasRecordService;
    @Resource
    private OneUserService oneUserService;
    @Resource
    private StoreService storeService;

    @Resource(name = "ehcacheCacheProvider")
    private EhcacheCacheProvider cacheProvider;

    public UserTrasRecordController() {
        super("callback");
    }

    /**
     * 确认付款
     * @param giftId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/receiveConfirm", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult receiveConfirm(String giftId,  String token, String userId) {
        JSONResult jsonResult = new JSONResult();
        if (!cacheProvider.get(userId).equals(token)) {
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        UserTrasRecord userTrasRecord = userTrasRecordService.findById(giftId);
        userTrasRecord.setStatus("2");
        userTrasRecordService.receiveConfirm(userTrasRecord);
        jsonResult.setCode("1");
        return jsonResult;
    }

    /**
     * 确认收款
     * @param giftId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/sendConfirm", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult sendConfirm(String giftId,  String token, String userId) {
        JSONResult jsonResult = new JSONResult();
        if (!cacheProvider.get(userId).equals(token)) {
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        UserTrasRecord userTrasRecord = userTrasRecordService.findById(giftId);
        userTrasRecord.setStatus("1");
        userTrasRecordService.sendConfirm(userTrasRecord);
        jsonResult.setCode("1");
        return jsonResult;
    }

    /**
     * 查询超级转账
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getTransFlag", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult getTransFlag(String token, String userId) {
        JSONResult jsonResult = new JSONResult();
        if (!cacheProvider.get(userId).equals(token)) {
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        jsonResult.setData(100);
        jsonResult.setCode("1");
        return jsonResult;
    }

    /**
     * 设置超级转账
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/setTransFlag", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult setTransFlag( String token, String userId) {
        JSONResult jsonResult = new JSONResult();
        if (!cacheProvider.get(userId).equals(token)) {
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        jsonResult.setData(100);
        jsonResult.setCode("1");
        return jsonResult;
    }

    /**
     * 验证交易短信
     * @param userId
     * @param actionId
     * @param vCode
     * @return
     */
    @RequestMapping(value = "/confirmTransaction", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult userTransaction(String actionId,String vCode ,String token, String userId) {
        JSONResult jsonResult = new JSONResult();
        if (!cacheProvider.get(userId).equals(token)) {
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        Map params = new HashMap();
        params = (Map) cacheProvider.get(actionId);
        String sendVCode=(String)params.get("vCode");

        if(!vCode.equals(sendVCode)){
            jsonResult.setCode("-1");
            jsonResult.setMsg("验证失败，请重新发起验证|Validation failed, please restart validation");
            return jsonResult;
        }


        String loginName= params.get("friendLoginName").toString();
        String senderId = params.get("userId").toString();

        OneUser sendOneUser = oneUserService.findByUserId(senderId);
        OneUser oneUser = oneUserService.findByLoginName(loginName);

        if(oneUser==null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("该用户不存在！");
            return jsonResult;
        }


        UserTrasRecord userTrasRecord = new UserTrasRecord();
        userTrasRecord.setSenderId(senderId);
        userTrasRecord.setReceiveId(oneUser.getUserId());
        userTrasRecord.setLoginName(sendOneUser.getLoginName());
        if(params.get("chickenNum")!=null){
            userTrasRecord.setGiftType("1");
            userTrasRecord.setGiftNum(new BigDecimal(params.get("chickenNum").toString()));
            userTrasRecord.setStatus("0");
        }
        if(params.get("eggNum")!=null){
            userTrasRecord.setGiftType("2");
            userTrasRecord.setGiftNum(new BigDecimal(params.get("eggNum").toString()));
            userTrasRecord.setStatus("0");
        }
        String msg = userTrasRecordService.add(userTrasRecord);
        if(msg==null) {
            jsonResult.setCode("1");
        }else{
            jsonResult.setCode("-1");
            jsonResult.setMsg(msg);
        }
        return  jsonResult;

    }


    /**
     * 设置超级转账
     *
     * @param jsonStr
     * @return
     */
    @RequestMapping(value = "/userTransaction", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult userTransaction(String jsonStr,String token) {
        JSONResult jsonResult = new JSONResult();

        ObjectMapper mapper = new ObjectMapper();
        Map params = new HashMap();
        try {
            params = mapper.readValue(jsonStr, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String loginName = params.get("friendLoginName").toString();
        String senderId = params.get("userId").toString();
        if (!cacheProvider.get(senderId).equals(token)) {
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }



        OneUser sendOneUser = oneUserService.findByUserId(senderId);
        OneUser oneUser = oneUserService.findByLoginName(loginName);


        Store sendStore = storeService.findByUserId(senderId);
        BigDecimal giftNum = null;
        String msg = null;
        if(params.get("chickenNum")!=null){
            giftNum= new BigDecimal(params.get("chickenNum").toString());
            msg = sendStore.getChicksNum().compareTo(giftNum) == -1?"帐号小鸡数量不足！":null;
        }
        if(params.get("eggNum")!=null){
            giftNum= new BigDecimal(params.get("eggNum").toString());
            msg = sendStore.getEggsNum().compareTo(giftNum) == -1?"帐号鸡蛋数量不足！":null;
        }
        if(msg!=null){
            jsonResult.setCode("-1");
            jsonResult.setMsg(msg);
            return  jsonResult;
        }

        String actionId = StringUtils.getUUID();
        String VCode= SMSWebChinese.sendSMS(sendOneUser.getPhone());
        if(VCode==null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("发送短信验证码出错！");
            return jsonResult;
        }
        //发送短信验证码
        params.put("vCode", VCode);

        cacheProvider.put(actionId, params);

        jsonResult.setCode("1");
        jsonResult.setData(actionId);
        return jsonResult;
    }

    /**
     * 查询用户交易记录
     *
     * @param type
     * @param userId
     * @param currentPage
     * @param numPerPage
     * @return
     */
    @RequestMapping(value = "/getUserTrasRecord", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult getUserTrasRecord(String type, String userId, Integer currentPage, Integer numPerPage,String token) {
        JSONResult jsonResult = new JSONResult();
        if (!cacheProvider.get(userId).equals(token)) {
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        Map rs = new HashMap();
        String senderId = null;
        String receiveId = null;

        if (type.equals("0")) {
            senderId = userId;
            receiveId = userId;
        }
        if (type.equals("1")) {
            senderId = userId;
        }
        if (type.equals("2")) {
            receiveId = userId;
        }

        Integer totalCount = userTrasRecordService.countNum(senderId, receiveId);
        List<UserTrasRecord> recordList = userTrasRecordService.findByPage(senderId, receiveId, numPerPage, currentPage);

        rs.put("currentPage", currentPage);
        rs.put("numPerPage", numPerPage);
        rs.put("totalCount", totalCount);
        rs.put("recordList", recordList);
        rs.put("pageCount", totalCount % numPerPage == 0 ? totalCount / numPerPage : totalCount / numPerPage + 1);
        rs.put("beginPageIndex", 1);
        rs.put("beginRowIndex", 0);
        rs.put("countResultMap", null);
        jsonResult.setCode("1");
        jsonResult.setData(rs);
        return jsonResult;
    }
}
